import { Cluster, Vector as VectorSource } from 'ol/source';
import { Vector as VectorLayer } from 'ol/layer';
import { GeoJSON, WFS } from "ol/format";
// import { Circle as CircleStyle, Fill, Stroke, Style, Text } from 'ol/style';
// import { get as getProjection } from 'ol/proj.js';
// import { matrixIds, resolutions } from './4326tilegridsets'
// import WMTS from 'ol/source/WMTS.js';
// import WMTSTileGrid from 'ol/tilegrid/WMTS.js';
// import TileLayer from 'ol/layer/Tile.js';
// import { getWidth, getTopLeft } from 'ol/extent.js';
// import Feature from 'ol/Feature';
// import Point from 'ol/geom/Point';
import { getStyle } from './style'
import { layerConfig } from '@/config/config'
// import axios from 'axios';
import { getGeoSource } from '@/api/geoApi'
import { Message } from 'element-ui';

// const pointSource = new VectorSource({
//     url: 'http://localhost:8080/geoserver/xmdata/wfs?service=WFS&version=1.1.0&request=GetFeature&' +
//         'typename=xmdata:xm_shoppoint' +
//         '&outputFormat=application/json&srsname=EPSG:4326',
//     format: new GeoJSON({
//         geometryName: 'geom'
//     }),
//     // features: new GeoJSON().readFeatures()
// });

export const getLayer = async (featureTypes, zindex) => {
    let layer

    let source = await getSource(featureTypes)

    layer = new VectorLayer({
        // 自定义name字段
        name: featureTypes,
        source: source,
        style: (feature) => {
            let size = featureTypes === 'xm_shoppoint' ? feature.get('features').length : ''
            return getStyle(featureTypes, false, size)
        },
        // 显示的层级
        zIndex: zindex
    });

    return layer
}

export const getSource = async (featureTypes) => {
    // ------------------------------------------------------------------
    // wfs
    let source, clusterSource

    let body = new WFS().writeGetFeature({
        srsName: "EPSG:4326", //坐标系
        featureNS: layerConfig.featureNS, // 注意这个值必须为创建工作区时的命名空间URI
        featurePrefix: layerConfig.featurePrefix, //工作区的命名
        featureTypes: [featureTypes], //所要访问的图层
        outputFormat: "application/json",
    })

    let req = new XMLSerializer().serializeToString(body)
    // let contentType = { 'Content-Type': 'text/plain; charset=UTF-8' }

    let res = await getGeoSource(req)
    if (res.status === 200) {
        let features = new GeoJSON({ geometryName: 'geom', }).readFeatures(res.data);
        source = new VectorSource();
        source.addFeatures(features)
    } else {
        Message.error(`获取图层 ${featureTypes} 失败`);
        return
    }

    // await axios.post(layerConfig.baseUrl, req, {
    //     headers: contentType
    // }).then((response) => {
    //     let features = new GeoJSON({ geometryName: 'geom', }).readFeatures(response.data);
    //     source = new VectorSource();
    //     source.addFeatures(features)
    // }).catch((error) => {
    //     console.log(error)
    // })
    // await fetch(layerConfig.baseUrl, {
    //     method: "post",
    //     body: new XMLSerializer().serializeToString(body),
    // }).then((response) => {
    //     return response.json();
    // }).then((json) => {
    //     // 格式要素
    //     let features = new GeoJSON({ geometryName: 'geom', }).readFeatures(json);
    //     source = new VectorSource();
    //     source.addFeatures(features)
    // });

    if (featureTypes === 'xm_shoppoint') {
        clusterSource = new Cluster({
            distance: 50,
            source: source
        })
        return clusterSource
    } else {
        return source
    }


    // ---------------------------------------------------------------------
    // wmts
    // let projection = getProjection('EPSG:4326');
    // let projectionExtent = projection.getExtent();
    // let matrixId = matrixIds
    // let resolution = resolutions

    // let layer = new TileLayer({
    //     name: featureTypes,
    //     source: new WMTS({
    //         url: 'http://localhost:8080/geoserver/gwc/service/wmts',
    //         layer: `xmdata:${featureTypes}`,
    //         matrixSet: 'EPSG:4326',
    //         format: 'image/png',
    //         projection: projection,
    //         tileGrid: new WMTSTileGrid({
    //             origin: getTopLeft(projectionExtent),
    //             resolutions: resolution,
    //             matrixIds: matrixId
    //         }),
    //         wrapX: true
    //     }),
    //     style: new Style({
    //         fill: new Fill({
    //             color: 'rgba(8, 131, 216, 0.2)',
    //         }),
    //         stroke: new Stroke({
    //             color: '#0883d8',
    //             width: featureTypes == 'xm_lrdl' ? 3 : '',
    //         }),
    //         image: new CircleStyle({
    //             radius: 7,
    //             fill: new Fill({
    //                 color: '#0883d8',
    //             }),
    //         }),
    //     }),
    //     zIndex: zindex
    // })
}

// 跨域问题
// https://www.cnblogs.com/ejQiu-123/p/11196963.html